package edu.ssm.campusAssistant.service.impl;

import com.github.pagehelper.PageHelper;
import edu.ssm.campusAssistant.bo.DemoBO;
import edu.ssm.campusAssistant.bo.QueryDemoListReq;
import edu.ssm.campusAssistant.bo.rsp.RspPageBO;
import edu.ssm.campusAssistant.constant.RspConstants;
import edu.ssm.campusAssistant.dao.DemoDao;
import edu.ssm.campusAssistant.exception.BusinessException;
import edu.ssm.campusAssistant.po.DemoPO;
import edu.ssm.campusAssistant.service.QueryDemoListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 标题:分页查询例子服务实现
 * 描述:
 *
 * @autho LXF
 * @date 2019/4/8 17:49
 */
@Service
public class QueryDemoListServiceImpl implements QueryDemoListService {
    private static final Logger logger = LoggerFactory.getLogger(QueryDemoListServiceImpl.class);
    private final boolean isDebugEnabled = logger.isDebugEnabled();
    @Autowired
    private DemoDao demoDao;

    @Override
    public RspPageBO<DemoBO> queryDemoList(QueryDemoListReq queryDemoListReq) {
        if (isDebugEnabled) {
            logger.debug("分页查询例子服务入参{}" + queryDemoListReq.toString());
        }
        RspPageBO<DemoBO> rspPageBO = null;
        try {
            //开启分页
            PageHelper.startPage(queryDemoListReq.getPageNo(), queryDemoListReq.getPageSize());
            //分页查询
            List<DemoPO> demoPOS = demoDao.selectDemoList(queryDemoListReq.getUserName());
            //设置分页返回参数
            rspPageBO = new RspPageBO<DemoBO>(demoPOS);
            //设置分页查询数据
            setRspPageBO(rspPageBO, demoPOS);
        } catch (Exception e) {
            logger.error("分页查询例子服务失败", e);
            throw new BusinessException(RspConstants.RSP_CODE_BUSI_SERVICE_ERROR, "分页查询例子服务失败");
        }
        return rspPageBO;
    }

    /**
     * 设置分页查询数据
     *
     * @param rspPageBO 分页返回参数
     * @param demoPOS   分页查询数据
     */
    private void setRspPageBO(RspPageBO<DemoBO> rspPageBO, List<DemoPO> demoPOS) {
        List<DemoBO> demoBOS = new ArrayList<DemoBO>();
        for (DemoPO demoPO : demoPOS) {
            DemoBO demoBO = new DemoBO();
            demoBO.setUserName(demoPO.getUserName());
            demoBO.setPassword(demoPO.getPassword());
            demoBOS.add(demoBO);
        }
        rspPageBO.setList(demoBOS);
    }
}
